<template>
  <div class="box">
    <h1>各学院 预储/社团 男女人数</h1>
    <div class="chart" ref="chart"></div>
  </div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import { onMounted, onUnmounted, ref } from 'vue';
import { getLeftTopMainChartData } from '@/api/data-screen/LeftChart';

import { useRouter } from 'vue-router';
const router = useRouter();

// 存储学院数据
const collegeDataRef = ref<CollegeData[]>([]);

// 处理柱子点击事件
const handleBarClick = (params: any) => {
  if (!params.dataIndex && params.dataIndex !== 0) return;

  const collegeIndex = params.dataIndex;
  const college = collegeDataRef.value[collegeIndex];
  if (!college) return;

  // 根据系列ID判断点击的是哪部分数据
  if (params.seriesId === 'preMale') {
    console.log(`点击了 ${college.collegeName} 学院的预储男生，人数: ${college.preReserve.male}`);
  } else if (params.seriesId === 'preFemale') {
    console.log(`点击了 ${college.collegeName} 学院的预储女生，人数: ${college.preReserve.female}`);
  } else if (params.seriesId === 'clubMale') {
    console.log(`点击了 ${college.collegeName} 学院的社团男生，人数: ${college.club.male}`);
  } else if (params.seriesId === 'clubFemale') {
    console.log(`点击了 ${college.collegeName} 学院的社团女生，人数: ${college.club.female}`);
  } else if (params.seriesId === 'preCount') {
    console.log(`点击了 ${college.collegeName} 学院的预储总人数: ${college.totalPre}`);
  } else if (params.seriesId === 'clubCount') {
    console.log(`点击了 ${college.collegeName} 学院的社团总人数: ${college.totalClub}`);
  }

  // 这里可以添加自定义逻辑，如弹出详情窗口等
};

// 后端数据接口定义
interface CollegeData {
  collegeName: string;
  preReserve: {
    male: number;
    female: number;
  };
  club: {
    male: number;
    female: number;
  };
  totalPre: number;
  totalClub: number;
}

// 获取数据的API
const fetchData = async () => {
  try {
    return (await getLeftTopMainChartData()).data;
  } catch (error) {
    console.error('获取数据失败:', error);
    return [];
  }
};

const chart = ref<HTMLElement | null>(null);
// 初始化
let chartInstance: echarts.ECharts | null = null;
const initChart = () => {
  if (chart.value) {
    chartInstance = echarts.init(chart.value);
    updateChart();
  }
};

const updateChart = async () => {
  try {

    // 从后端获取数据
    const collegeData = await fetchData();
    // 计算总和
    const preTotal = collegeData.map(item => -(item.preReserve.male + item.preReserve.female));
    const clubTotal = collegeData.map(item => item.club.male + item.club.female);
    // 处理数据
    const college = collegeData.map(item => item.collegeName.split('').join('\n'));
    const preMale = collegeData.map(item => -item.preReserve.male);
    const preFemale = collegeData.map(item => -item.preReserve.female);
    const clubMale = collegeData.map(item => item.club.male); // 负值用于反向堆叠
    const clubFemale = collegeData.map(item => item.club.female);
    // 计算 Y 轴的最大值和最小值
    const allValues = [...preMale, ...preFemale, ...clubMale, ...clubFemale];
    const maxValue = Math.max(...allValues.map(Math.abs)) + 40; // 取绝对值的最大值
    // const minValue = -Math.min(...allValues.map(Math.abs)) + 40; // 取绝对值的最大值
    const minValue = -maxValue + 30; // 最小值为负的最大值



    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' },
        formatter: function (params) {
          let tip = params[0].name.replace(/\n/g, '') + '<br/>';
          params.forEach((item) => {
            if (item.seriesId.includes('preCount')) {
              // 如果是“预储”总和系列，显示对应的总和值，并添加“预储”标签
              const dataIndex = item.dataIndex;
              const totalValue = Math.abs(preTotal[dataIndex]); // 预储总和
              tip += `${item.marker} 预储 总和: ${totalValue}<br/>`;
            } else if (item.seriesId.includes('clubCount')) {
              // 如果是“社团”总和系列，显示对应的总和值，并添加“社团”标签
              const dataIndex = item.dataIndex;
              const totalValue = Math.abs(clubTotal[dataIndex]); // 社团总和
              tip += `${item.marker} 社团 总和: ${totalValue}<br/>`;
            } else {
              // 其他系列正常显示
              const category = item.seriesId.includes('pre') ? '预储' : '社团';
              const val = Math.abs(item.value);
              tip += `${item.marker} ${category} ${item.seriesName}: ${val}<br/>`;
            }
          });
          return tip;
        }
      },
      legend: {
        data: ['男', '女', '总和'],
        top: 21,
        textStyle: {
          fontSize: 16,  // 设置字体大小
          color: '#ccc'  // 设置字体颜色
        },
        selected: {
          '男': true,  // 默认选择男
          '女': true   // 默认选择女
        }
      },
      grid: {
        left: '8%',
        right: '2%',
        bottom: '0%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: college,
          axisLabel: {
            color: '#ccc',
            fontSize: 16,
            fontWeight: 'bold',
            interval: 0,
            align: 'center',
            verticalAlign: 'top'
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#000000',
              width: 1
            }
          },
          axisTick: { show: false }
        }
      ],
      yAxis: [
        {
          type: 'value',
          nameLocation: 'end',
          name: '军事兴趣社团/人',
          nameTextStyle: {
            color: '#00BFFF',
            fontSize: 15,
            fontWeight: 'bold',
            padding: [0, 4, 0, 0]//Y轴标题位置
          },
          axisLabel: {
            formatter: function (value) {
              return Math.abs(value);
            }
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: '#ccc',
              width: 1
            }
          },
          axisTick: {
            show: true//刻度
          },
          z: 10,  // 设置更高的 z 值来确保 Y 轴的线在最上层
          min: minValue, // 动态设置最小值
          max: maxValue, // 动态设置最大值
          splitNumber: 5 // 分割段数
        }
      ],
      graphic: [
        {
          type: 'text',
          left: '8px',
          top: '76%',
          style: {
            text: '预储/人',
            fill: '#00BFFF',
            fontSize: 15,
            fontWeight: 'bold'
          }
        }
      ],
      series: [
        {
          name: '男',
          id: 'clubMale',
          type: 'bar',
          stack: 'post',
          itemStyle: { color: '#63B8FF' },
          label: { show: true, position: 'insideTop' },
          data: clubMale,
          z: 5, // 设置较低的 z 值
          legendHoverLink: true,
        },
        {
          name: '女',
          id: 'clubFemale',
          type: 'bar',
          stack: 'post',
          itemStyle: { color: '#FF6EB4' },
          label: { show: true, position: 'insideTop' },
          data: clubFemale,
          z: 15,  // 
          legendHoverLink: true,
        },
        {
          name: '总和',
          id: 'clubCount',
          type: 'bar',
          stack: 'post',
          itemStyle: { color: '#ccc' },
          barWidth: '80%',
          label: {
            show: true,
            position: 'top',
            color: '#ccc',
            fontWeight: 'bold',
            formatter: function (params) {
              return Math.abs(clubTotal[params.dataIndex]);
            }
          },
          data: new Array(18).fill(0),
          z: 15  // 设置更高的 z 值，确保它位于最顶层
        },
        {
          name: '男',
          id: 'preMale',
          type: 'bar',
          stack: 'pre',
          itemStyle: { color: '#87CEFA' },
          label: {
            show: true,
            position: 'insideBottom',
            offset: [0, 5],    // 向下偏移 5px
            padding: [0, 0, 0, 0], // 可选：增加底部内边距
            formatter: ({ value }) => Math.abs(value)
          },
          data: preMale,
          z: 15,
          legendHoverLink: true,
        },
        {
          name: '女',
          id: 'preFemale',
          type: 'bar',
          stack: 'pre',
          itemStyle: { color: '#FF82AB' },
          label: {
            show: true,
            position: 'insideBottom',
            offset: [0, 5],    // 向下偏移 5px
            padding: [0, 0, 0, 0], // 可选：增加底部内边距
            formatter: ({ value }) => Math.abs(value)
          },
          data: preFemale,
          z: 15,  // 设置较低的 z 值
          legendHoverLink: true,
        },
        {
          name: '总和',
          id: 'preCount',
          type: 'bar',
          stack: 'pre',
          itemStyle: { opacity: 1 },
          barWidth: '80%',
          label: {
            show: true,
            position: 'bottom',
            color: '#ccc',
            fontWeight: 'bold',
            formatter: function (params) {
              return Math.abs(preTotal[params.dataIndex]);
            }
          },
          data: new Array(18).fill(0),
          z: 15  // 设置更高的 z 值，确保它位于最顶层
        },
      ],
      barCategoryGap: '20%',
      barGap: '-100%'
    };
    option && chartInstance.setOption(option);

    // 绑定点击事件
    chartInstance.on('click', function (params) {
      // 确保点击的是柱状图系列
      if (params.componentType === 'series' && params.seriesType === 'bar') {
        const collegeName = params.name.replace(/\n/g, ''); // 获取学院名称
        const value = params.value as number; // 获取柱子的值  类型断言为 number
        const seriesName = params.seriesName; // 获取系列名称（如“男”或“女”）

        if (value > 0) {
          // 点击上半部分：社团数据
          // alert(`学院: ${collegeName}\n类别: 社团\n性别: ${seriesName}\n数量: ${value}`);

          router.push({
            path: '/admin/activeManage',
            query: {
              college: collegeName,
              gender: seriesName === '男' ? 1 : 0,
              page: 1,
              pageSize: 5,
            }
          })

        } else if (value < 0) {
          // 点击下半部分：预储数据
          const absValue = Math.abs(value); // 取绝对值显示实际数量
          // alert(`学院: ${collegeName}\n类别: 预储\n性别: ${seriesName}\n数量: ${absValue}`);

          router.push({
            path: '/admin/preReserve/memberManage',
            query: {
              college: collegeName,
              gender: seriesName === '男' ? 1 : 0,
              page: 1,
              pageSize: 5,
            }
          })

        }
      }
    });

  } catch (error) {
    console.log('获取左上图失败！')
  }
}


let resizeHandler: () => void;
onMounted(() => {
  initChart();
  resizeHandler = () => {
    if (chartInstance) {
      chartInstance.resize();
    }
  };

  window.addEventListener('resize', resizeHandler);
})

onUnmounted(() => {
  window.removeEventListener('resize', resizeHandler);
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
});

</script>

<style scoped>
.box {
  height: 100%;
  width: 100%;
  align-items: center;
  justify-content: center;
}

.chart {
  height: 85%;
  width: 97%;
}

h1 {
  text-align: center;
  color: aliceblue;
  margin: 0;
  margin-top: 1rem;
  padding: 0;
}
</style>